<template>
  <div class="layer-tree-container" >
    <el-tree
      ref="treeRef"
      :data="treeData"
      :props="treeProps"
      show-checkbox
      node-key="id"
      :default-expanded-keys="defaultExpandedKeys"
      @check="handleCheckChange"
    >
      <template #default="{ node, data }">
        <div class="custom-tree-node">
          <!-- 节点名称 -->
          <span>{{ node.label }}</span>
        </div>
      </template>
    </el-tree>
    <div class="close" @click="closeTree">
      <span>X</span>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick,defineEmits,getCurrentInstance } from 'vue'
import type { ElTree } from 'element-plus'

import layerTreeData from "/public/data/tree-data.ts";
// 定义要发射的事件
const emit = defineEmits(['toggle-layer','close']);
const instance = getCurrentInstance();
const EventBus = instance.appContext.config.globalProperties.EventBus;

interface TreeDataNode {
  id: string
  name: string
  checked?: boolean
  children?: TreeDataNode[]
  // 保留原始数据以便操作
  raw: any
  // 用于 v-model 绑定的响应式透明度属性
  opacity?: number
}

// --- 响应式状态 ---
const treeRef = ref<InstanceType<typeof ElTree>>()
const treeData = ref<TreeDataNode[]>([])
const treeProps = {
  children: 'children',
  label: 'name',
}
const defaultExpandedKeys = ref<string[]>([]) 

const processData = (nodes: any[]): TreeDataNode[] => {
  return nodes.map(node => {
    const isFeature = node.type === 'Feature'
    const properties = isFeature ? node.properties : node
    
    const newNode: TreeDataNode = {
      id: properties.id,
      name: properties.name,
      checked: properties.checked || false,
      raw: node, // 保存原始节点数据
    }

    // 为可控制透明度的图层初始化 opacity 属性
    // 这里我们主要处理 imagery 图层
    if (isFeature && properties.props?.imagery) {
      newNode.opacity = properties.props.imagery.alpha ?? 1.0
    }
    // 您可以在这里为其他类型如图 tileset, geojson 添加透明度逻辑
    // 例如，对于 tileset，您可能需要通过 Cesium3DTileStyle 来控制
    // 对于 geojson，您可能需要解析 fill 或 stroke 的 rgba 值

    if (node.children && node.children.length > 0) {
      newNode.children = processData(node.children)
    }

    return newNode
  })
}

/**
 * 递归获取初始状态下需要被勾选的节点的 key (id)
 * @param nodes 格式化后的节点数组
 * @returns key 数组
 */
const getInitialCheckedKeys = (nodes: TreeDataNode[]): string[] => {
  let keys: string[] = []
  nodes.forEach(node => {
    // 只勾选叶子节点，父节点状态会由 element-plus 自动处理
    if (node.checked && !node.children) {
      keys.push(node.id)
    }
    if (node.children) {
      keys = keys.concat(getInitialCheckedKeys(node.children))
    }
  })
  return keys
}

// --- 事件处理函数 ---

/**
 * 判断节点是否拥有透明度控制器
 * @param data 节点数据
 */
const hasOpacityControl = (data: TreeDataNode): boolean => {
  // 目前只为 imagery 类型的图层显示滑块
  return !!data.raw.properties?.props?.imagery
}

/**
 * 复选框状态改变时的回调
 * @param data 点击的节点数据
 * @param checkedNode 包含节点本身和所有半选节点的详细信息
 */
const handleCheckChange = (data: TreeDataNode, checkedNode: { checkedKeys: string[], halfCheckedKeys: string[] }) => {
  
  const isChecked = checkedNode.checkedKeys.includes(data.id)
  debugger
  let layerIds = []
  if (data?.children?.length) {
    layerIds = data.children.map(item => item.id);
  }else{
    layerIds = [data.id]
  }
  console.log(`图层 "${data.name}" (ID: ${data.id}) 的状态变为: ${isChecked ? '显示' : '隐藏'}`)

  EventBus.emit('toggle-Layer', {layerIds:layerIds,isShow: isChecked});
}

/**
 * 3. ADDED: 递归获取初始状态下需要展开的节点的 key (id)
 * @param nodes 格式化后的节点数组
 * @returns key 数组
 */
const getInitialExpandedKeys = (nodes: TreeDataNode[]): string[] => {
  let keys: string[] = []
  nodes.forEach(node => {
    // 从原始数据中检查 expanded 属性
    if (node.raw.expanded) {
      keys.push(node.id)
    }
    if (node.children) {
      keys = keys.concat(getInitialExpandedKeys(node.children))
    }
  })
  return keys
}
/**
 * 透明度滑块值改变时的回调
 * @param data 节点数据
 * @param newOpacity 新的透明度值
 */
const handleOpacityChange = (data: TreeDataNode, newOpacity: number) => {
  console.log(`图层 "${data.name}" (ID: ${data.id}) 的透明度变为: ${newOpacity}`)

  // 同步更新原始数据中的 alpha 值，如果需要的话
  if (data.raw.properties?.props?.imagery) {
    data.raw.properties.props.imagery.alpha = newOpacity
  }

  EventBus.emit("toggleLayerOpcity", {layerId:data.id,opacity:newOpacity});
}
const closeTree = ()=>{
  emit("close")
}

// --- 生命周期钩子 ---
onMounted(() => {

  const processed = processData(layerTreeData)
  treeData.value = processed
 defaultExpandedKeys.value = getInitialExpandedKeys(processed)
  // 2. 获取初始勾选状态
  const initialKeys = getInitialCheckedKeys(processed)

  // 3. 在 DOM 更新后设置树的初始勾选状态
  nextTick(() => {
    const initialCheckedKeys = getInitialCheckedKeys(processed)
    treeRef.value?.setCheckedKeys(initialCheckedKeys, false)
  })
})
</script>

<style scoped lang='less'>
.layer-tree-container {
  position: absolute;
  top: 20vh;
  left: 10px;
  background-image: url(/img/底框.png);
  width: 250px;
  height: 60vh;
  overflow: auto;
  padding: 10px;
}

.custom-tree-node {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  font-size: 14px;
  padding-right: 8px; /* 给右侧留出空间 */
}

.opacity-slider {
  width: 120px; /* 限制滑块宽度 */
  margin-left: 10px; /* 与文字的间距 */
}

/* 优化 el-tree 样式，让内容撑满 */
:deep(.el-tree-node__content) {
  height: auto;
  min-height: 26px;
  padding-top: 4px;
  padding-bottom: 4px;
}

:deep(.el-tree) {
  background-color: transparent;
  color: #fff;

  .el-tree-node__content {
    &:hover {
      background-color: rgba(255, 255, 255, 0.2);
    }
  }
  .el-tree-node.is-current > .el-tree-node__content {
    background-color: rgba(255, 255, 255, 0.2);
    color: #fff;
  }
  .el-tree-node__expand-icon {
    color: #fff;
  }
  .el-tree-node:focus > .el-tree-node__content {
    //  background-color: transparent;
  }
}

.close{
    position: absolute;
    color: #fff;
    top: 5px;
    right: 8px;
    font-size: 15px;
    padding: 5px 10px;
}
</style>
